<template>
  <el-dialog title="添加角色" :visible.sync="isShow" @close="closeShow" :before-close="handleClose">
    <el-form ref="addForm" :model="roleForm" label-width="80px" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="roleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="closeShow()">取 消</el-button>
      <el-button type="primary" @click="addRoles()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  //接收父组件传值
  props: ['isShow'],
  data() {
    return {
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    closeShow() {
      this.$emit('setIsShow', false)
      this.$refs.addForm.resetFields()
    },
    //before-close 仅当用户通过点击关闭图标或遮罩关闭 Dialog 时起效
    handleClose() {
      this.closeShow()
    },
    addRoles() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          console.log(this.roleForm)
          const { data: res } = await this.$http.post('roles', this.roleForm)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            //添加成功后通知父组件刷新数据
            this.$emit('Refresh')
            this.closeShow()
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>